<?php
/**
 * Created by PhpStorm.
 * User: Lzhy ysjywz@gmail.com
 * Date: 2019/8/18
 * Time: 2:10 PM
 */
namespace app\wechat\logic;

use think\Db;

class Msg
{
    public static function handle($message,$app)
    {
        $iId = 0;
        try{
            $iId = self::_saveMsgAndUpdateAccTime($message);
        }catch (\Exception $e){
            return $e->getMessage();
        }
        switch($message['MsgType']){
            case 'event':
                return self::_eventHandle($message,$app,$iId);
                break;
            case 'text':
                return self::_textHandle($message,$app,$iId);
                break;
            case 'image':
                return '收到图片消息';
                break;
            case 'voice':
                return '收到语音消息';
                break;
            case 'video':
                return '收到视频消息';
                break;
            case 'location':
                return '收到坐标消息';
                break;
            case 'link':
                return '收到链接消息';
                break;
            case 'file':
                return '收到文件消息';
            default:
                return '收到其它消息';
                break;
        }
    }
    
    private static function _eventHandle($message,$app,$iId)
    {
        $event = $message['Event'];
        $openid = $message['FromUserName'];
        $wechatId = $message['ToUserName'];
        if($event === 'subscribe'){
            try{
                $user = $app->user->get($openid);
                $data = [
                    'sex' => $user['sex'],
                    'city' => $user['city'],
                    'openid' => $openid,
                    'country' => $user['country'],
                    'province' => $user['province'],
                    'nickname' => $user['nickname'],
                    'subscribe' => 1,
                    'headimgurl' => $user['headimgurl'],
                    'subscribe_time'  => $user['subscribe_time'],
                    'subscribe_scene' => $user['subscribe_scene'],
                    'unionid' => $user['unionid'] ?? '',
                    'acc_time' => time(),
                    'wechat_id' => $wechatId,
                    'update_time' => date('Y-m-d H:i:s'),
                ];
                $eId = Db::table('wuser')->where('openid',$openid)->value('id');
                if($eId){
                    Db::table('wuser')->where('openid',$openid)->update($data);
                }else{
                    $data['add_time'] = date('Y-m-d H:i:s');
                    Db::table('wuser')->insert($data);
                }
                return $user['nickname'].',您好。欢迎关注';
            }catch (\Exception $e){
                return $e->getLine().$e->getMessage();
            }
        }elseif($event === 'unsubscribe'){
            try{
                Db::table('wuser')->where('openid',$openid)->update(['subscribe'=>0,'update_time'=>date('Y-m-d H:i:s')]);
                return '';
            }catch (\Exception $e){

            }
        }elseif($event === 'CLICK'){

        }

        return '收到事件消息';
    }

    private static function _textHandle($message,$app,$iId)
    {
        try{
            $content = $message['Content'];
            $openid  = $message['FromUserName'];

            $nickname = Db::table('wuser')->where('openid',$openid)->value('nickname');
            $responseMsg = sprintf('%s您好,收到您的消息:%s,向你回复:%s',$nickname,$content,rand(0,999999));
            return $responseMsg;
        }catch (\Exception $e){

        }

        return '收到文本消息';
    }

    /**
     * 保存用户信息并更新最后交互时间
     */
    private static function _saveMsgAndUpdateAccTime($message)
    {
        $event = $message['Event'] ?? '';
        $openid   = $message['FromUserName'];
        $wechatId = $message['ToUserName'];
        $msgType  = $message['MsgType'];
        $createTime = $message['CreateTime'];
        $data = [
            'openid'   => $openid,
            'msg_type' => $msgType,
            'content'  => $message['Content'] ?? '',
            'media_id' => $message['MediaId'] ?? '',
            'msg_id'   => $message['MsgId'] ?? '',
            'event'    => $event,
            'event_key' => $message['EventKey'] ?? '',
            'wechat_id' => $wechatId,
            'create_time' => $createTime
        ];

        $iId = Db::table('wmsg')->insertGetId($data);
        if($event !== 'unsubscribe' && $event !== 'subscribe'){
            Db::table('wuser')->where('openid',$openid)->update(['subscribe'=>1,'acc_time'=>time(),'update_time'=>date('Y-m-d H:i:s')]);
        }

        return $iId;
    }
}